package network;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;

import msg.Message;
import protocol.ID;
import protocol.Node;
import protocol.Tapestry;
import protocol.TapestryID;
import time.Clock;
import event.Event;
/*
 * Created on 2005-3-11
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author Lizzy
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class Network {
	//map maps node's id to node.
	Hashtable<ID,Node> map;
	int delay;
	public Node wellKnownNode;
	static Network network;
	
	public static Network getInstance(){
		if(network == null)network = new Network();
		return network;
	}
	public void setDelay(int delay) {
		this.delay = delay;
	}
	Network(){
		map = new Hashtable<ID,Node>(500000);
		
	}
	public Enumeration getAllNodes(){
		return map.elements();
	}
/**
 * 
 * @param from 	index of sorce node
 * @param to	index of destination node
 * @return		latency between 2 nodes in mileseconds.
 */
	 int getLatency(Node from, Node to){
		return delay;
//		Position f=(Position) from.getPosition();
//		Position t=(Position) to.getPosition();
//		return (int)Math.sqrt((f.x-t.x)*(f.x-t.x)+(f.y-t.y)*(f.y-t.y));
	}
	/**
	 * 
	 * @param id	id of a node
	 * @return		index of a node
	 */
	void putNode(Node n){
		map.put(n.id,n);
	}
	Node getNode(Integer id){
		return (Node)map.get(id);
	}
	public void send(Node from,Node to,Message msg){
		ID fromid=from.id;
		ID toid=to.id;
		int delay=getLatency(from,to);		
		Event e = new Event(Event.LOOKUP,Clock.now(),from,to,msg); 
	}
	public void paser(String networkFile){
		int number=0;
		int delay=0;
		int dimention = 0;
		try{
			BufferedReader br = new BufferedReader(new FileReader(networkFile));
			String line;
			StringTokenizer st;
			while ((line = br.readLine())!=null){
				st=new StringTokenizer(line);
				if(st.countTokens()!=3){
					System.err.println("networkFile format:number delay dimention");
				}
				number = new Integer(st.nextToken()).intValue();
				delay  = new Integer(st.nextToken()).intValue();
				dimention = new Integer(st.nextToken()).intValue();
			    ID.setBase(dimention);
			}
		}catch(Exception e){
		
		}
		//set delay
		setDelay(delay);
		//crate wellknown node:
		wellKnownNode = new Tapestry(0,null);
		this.putNode(wellKnownNode);
				//crate nodes
		
		for (int i = 1; i < number; i++) {
			this.putNode(new Tapestry(i,null));
		}
		
		System.out.println(number+" nodes has been created. One hop delay is "+delay);
	}
	public int getDelay() {
		return delay;
	}
}

class Position{
	int x;
	int y;
	Position(int x, int y){
		this.x=x;
		this.y=y;
	}
}